﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.IO.IsolatedStorage;
using System.IO;
using System.Diagnostics;
using System.Xml.Linq;

namespace ByrForum
{
    public partial class UpdatePost : PhoneApplicationPage
    {
        string _newContent = "";
        string _newTitle = "";
        bool if_loaded = false;
        string boardname = "";
        string _id = "";
        public UpdatePost()
        {
            InitializeComponent();
            IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
            String title = (String)settings["title"];
            String content=(String)settings["content"];
            this.textBoxNewTitle.Text = title;
            this.textBoxNewContent.Text = content;
        }
        private void buttonSubmit_Click(object sender, RoutedEventArgs e)
        {
            if (textBoxNewContent.Text == "" || textBoxNewTitle.Text == "")
            {
                MessageBox.Show("标题或内容不能为空！");
                return;
            }
            _newContent = textBoxNewContent.Text;
            _newTitle = textBoxNewTitle.Text;
            string url = ByrApi.apiUrl + "/article/" + boardname + "/update"+"/"+ _id+ ByrApi.Encode + ByrApi.appkey;
            HttpUtil.HttpPost(url, PostAriticle_Callback);
        }
        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            if (!if_loaded)
            {

                IDictionary<string, string> queryString = this.NavigationContext.QueryString;
                try
                {
                    queryString.TryGetValue("id", out _id);
                    queryString.TryGetValue("boardname", out boardname);
                }
                catch
                {
                    base.OnNavigatedTo(e);
                    return;
                }
                if_loaded = true;

            }
        }
        private void PostAriticle_Callback(IAsyncResult asynchronousResult)
        {

            try
            {
                HttpWebRequest hwrq = (HttpWebRequest)asynchronousResult.AsyncState;

                Stream responseStream = hwrq.EndGetRequestStream(asynchronousResult);
                StreamWriter sr = new StreamWriter(responseStream);
                sr.Write("title=" + _newTitle + "&content=" + _newContent + "\n\n\n来自：Windows Phone 7 客户端-alpha" + "&signature=1");
                sr.Close();
                responseStream.Close();
                hwrq.BeginGetResponse(PostResponse_Callback, hwrq);
            }
            catch (Exception e)
            {
                Debug.WriteLine("POST STRING FAILED:" + e.Message);
            }
        }
        private void PostResponse_Callback(IAsyncResult asynchronousResult)
        {
            try
            {
                string result = HttpUtil.ReadToEnd(asynchronousResult);
                XDocument doc = XDocument.Parse(result);
                Debug.WriteLine(result);
                foreach (XElement item in doc.Descendants("error").Nodes())
                {
                    if (item.Name == "msg")
                    {
                        this.Dispatcher.BeginInvoke(
                            () =>
                            {
                                MessageBox.Show("发帖失败：" + item.Value);

                            }
                            );


                        return;
                    }
                }
                this.Dispatcher.BeginInvoke(
                    () =>
                    {
                        MessageBox.Show("发帖成功！");
                        this.NavigationService.GoBack();
                    }
                    );
            }
            catch { }



        }

        private void buttonCancel_Click(object sender, RoutedEventArgs e)
        {
            if (this.NavigationService.CanGoBack)
                this.NavigationService.GoBack();
        }
    }
}